//
//  MYImageDownloader.m
//  GIFShow
//
//  Created by lanou11air029 on 15/3/28.
//  Copyright (c) 2015年 CK. All rights reserved.
//

#import "MYImageDownloader.h"
#import <CommonCrypto/CommonCrypto.h>
#import <CoreData/CoreData.h>
@interface MYImageDownloader ()
@property (strong, nonatomic) NSManagedObjectContext * managedContext;
@property (strong, nonatomic) NSString * url_Str;
@property (strong, nonatomic) NSString * urlMd5Str;
@property (strong, nonatomic) NSString * filePath;

@end
@implementation MYImageDownloader
-(NSData *)downloadUrlStr:(NSString *)urlStr{
    self.url_Str = urlStr;
    _urlMd5Str = nil;
    NSData * data = nil;
    if ([self isAlready]) {
        data = [[NSData alloc]initWithContentsOfFile:self.filePath];
    }else{
        __block NSData *blockData = data;
    dispatch_async(dispatch_get_main_queue(), ^{
        NSURL * url = [NSURL URLWithString:urlStr];
        blockData = [[NSData alloc]initWithContentsOfURL:url];
        [blockData writeToFile:self.filePath atomically:YES];
    });
    }
    return data;
}
-(NSString *)urlMd5Str
{
    if (_url_Str) {
        if (_urlMd5Str) {
            return _urlMd5Str;
        }
        _urlMd5Str = [self makeMd5:self.url_Str];
    }else{
        NSLog(@"获取不到网址");
        _urlMd5Str = @"";
    }
    return _urlMd5Str;
}
-(NSString *)makeMd5:(NSString *)str{
    const char *cStr = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}
-(BOOL)isAlready{
    NSString * cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString * fileName = [NSString stringWithFormat:@"%@",self.urlMd5Str];
    self.filePath = [cachesPath stringByAppendingPathComponent:fileName];
    NSLog(@"%@",self.filePath);
   return [[NSFileManager defaultManager]fileExistsAtPath:self.filePath];
}
@end
